// 获取assets静态资源
// export const getAssetsFile = (filename, url) => {
//   console.log(filename, url);
//   // 获取文件夹下所有图片名称
//   // 使用静态字符串进行 glob 导入，然后在运行时过滤
//   const files = import.meta.glob('../assets/img/*/*.png', { eager: true });
//   const urlname = `../assets/img/${filename}/`;
//   // console.log(urlname);
//   let AllPics = Object.entries(files)
//     .filter(([path]) => path.startsWith(urlname))
//     .map(([, v]) => v.default);
//   let imgSrc = '';
//   // 遍历所有图片，判断是否存在该url图片
//   AllPics.forEach(val => {
//     if (val.indexOf(url) !== -1) {
//       imgSrc = val
//     }
//   });
//   console.log(imgSrc);
//   console.log(import.meta.url);
//   return new URL(imgSrc, import.meta.url).href;
// };
export const getAssetsFile = (filename, url) => {

  // console.log(filename, url);
  const files = import.meta.glob('../assets/img/*/*.png', { eager: true })
  const urlname = `../assets/img/${filename}/`
  const AllPics = Object.entries(files)
    .filter(([path]) => path.startsWith(urlname))
    .map(([, v]) => v.default)

  const imgSrc = AllPics.find((val) => val.includes(url)) || ''

  if (!imgSrc) {
    console.warn(`未找到匹配的图片: filename=${filename}, url=${url}`)
    return ''
  }

  // console.log(imgSrc);
  return new URL(imgSrc, import.meta.url).href
}

// 经纬度转度分秒
export const formatDMS = (decimal, secondsPrecision = 2, isLatitude = true) => {
  const absDecimal = Math.abs(decimal)

  const degrees = Math.floor(absDecimal)
  const remaining = absDecimal - degrees
  const minutes = Math.floor(remaining * 60)
  const seconds = ((remaining * 60 - minutes) * 60).toFixed(secondsPrecision)

  let direction = ''
  if (decimal >= 0) {
    direction = isLatitude ? 'N' : 'E'
  } else {
    direction = isLatitude ? 'S' : 'W'
  }

  return { degrees, minutes, seconds: Number(seconds), direction }
}

// 度分秒转经纬度
export const robustParseDMS = (dmsString) => {
  // 正则表达式匹配各种DMS格式
  const regex = /([-+]?)(\d{1,3})[°ºd: ]\s*(\d{1,2})['′m: ]\s*(\d{1,2}(?:\.\d+)?)[″"s ]?([NSEW]?)/i
  const match = dmsString.match(regex)

  if (!match) return NaN

  // 提取各部分
  const sign = match[1] === '-' ? -1 : 1
  const degrees = parseFloat(match[2])
  const minutes = parseFloat(match[3])
  const seconds = parseFloat(match[4])
  const direction = match[5].toUpperCase()

  // 计算十进制值
  let decimal = degrees + minutes / 60 + seconds / 3600

  // 根据方向字母确定正负
  if (direction === 'S' || direction === 'W') {
    decimal = -decimal
  } else if (direction === 'N' || direction === 'E') {
    decimal = decimal
  } else {
    // 如果没有方向字母，则使用符号位
    decimal = sign * decimal
  }

  return decimal
}

//航向

export const calculateHeading = (fromCartesian, toCartesian) => {
  // 将笛卡尔坐标转换为地理坐标（弧度）
  const from = Cesium.Cartographic.fromCartesian(fromCartesian)
  const to = Cesium.Cartographic.fromCartesian(toCartesian)

  // 转换为度数
  const fromLon = Cesium.Math.toDegrees(from.longitude)
  const fromLat = Cesium.Math.toDegrees(from.latitude)
  const toLon = Cesium.Math.toDegrees(to.longitude)
  const toLat = Cesium.Math.toDegrees(to.latitude)

  // 计算方位角（航向）
  const dLon = toLon - fromLon
  const y =
    Math.sin(dLon * Cesium.Math.RADIANS_PER_DEGREE) *
    Math.cos(toLat * Cesium.Math.RADIANS_PER_DEGREE)
  const x =
    Math.cos(fromLat * Cesium.Math.RADIANS_PER_DEGREE) *
      Math.sin(toLat * Cesium.Math.RADIANS_PER_DEGREE) -
    Math.sin(fromLat * Cesium.Math.RADIANS_PER_DEGREE) *
      Math.cos(toLat * Cesium.Math.RADIANS_PER_DEGREE) *
      Math.cos(dLon * Cesium.Math.RADIANS_PER_DEGREE)

  let heading = Math.atan2(y, x) * Cesium.Math.DEGREES_PER_RADIAN

  // 将结果归一化为0-360度
  return (heading + 360) % 360
}
/* 

*/

const armyMarkmap = new Map([
  [
    '船',
    {
      label: '船',
      value: 'ship',
      LibID: 10,
      Code: 6900,
    },
  ],
  [
    '飞机',
    {
      label: '飞机',
      value: 'plane',
      LibID: 10,
      Code: 7901,
    },
  ],
  [
    '雷达',
    {
      label: '雷达',
      value: 'radar',
      LibID: 10,
      Code: 13305,
    },
  ],
  [
    '雷达站',
    {
      label: '雷达站',
      value: 'radarStation',
      LibID: 10,
      Code: 13800,
    },
  ],
  [
    '指挥车',
    {
      label: '指挥车',
      value: 'commandVehicle',
      LibID: 10,
      Code: 5400,
    },
  ],
  [
    '指挥所',
    {
      label: '指挥所',
      value: 'commandPost',
      LibID: 10,
      Code: 2804,
    },
  ],
  [
    '超短波天线',
    {
      label: '超短波天线',
      value: 'ultraShortWaveAntenna',
      LibID: 64,
      Code: 308,
    },
  ],
  [
    '微波天线',
    {
      label: '微波天线',
      value: 'antenna',
      LibID: 64,
      Code: 298,
    },
  ],
  [
    '短波天线',
    {
      label: '短波天线',
      value: 'shortWaveAntenna',
      LibID: 64,
      Code: 307,
    },
  ],
  [
    '机场',
    {
      label: '机场',
      value: 'airport',
      LibID: 11,
      Code: 1001,
    },
  ],
  [
    '地标',
    {
      label: '地标',
      value: 'landmark',
      LibID: 11,
      Code: 1002,
    },
  ],
  [
    '未知固定点(圆图标)',
    {
      label: '未知固定点(圆图标)',
      value: 'unknownFixedPoint',
      LibID: 11,
      Code: 1000,
    },
  ],
  [
    '静目标',
    {
      label: '静目标',
      value: 'quietTarget',
      LibID: 11,
      Code: 1000,
    },
  ],
  [
    '动目标',
    {
      label: '动目标',
      value: 'movingTarget',
      LibID: 64,
      Code: 7901,
    },
  ],
  [
    '',
    {
      label: '静目标',
      value: 'quietTarget',
      LibID: 11,
      Code: 1000,
    },
  ],
  [
    undefined,
    {
      label: '静目标',
      value: 'quietTarget',
      LibID: 11,
      Code: 1000,
    },
  ],
])

/**
 * 从 armyMarkmap 中获取值的示例
 * @param {string|undefined} key - 用于查找的键
 * @returns {Object|undefined} - 匹配的值，如果未找到则返回 undefined
 */
export const getArmyMarkValue = (key) => {
  return armyMarkmap.get(key)
}

// 使用示例
// const shipData = getArmyMarkValue("船");
// console.log(shipData);

export const armyMarkobj = [
  {
    label: '船',
    value: 'ship',
    LibID: 10,
    Code: 6900,
  },
  {
    label: '飞机',
    value: 'plane',
    LibID: 10,
    Code: 7901,
  },
  {
    label: '雷达',
    value: 'radar',
    LibID: 10,
    Code: 13305,
  },
  {
    label: '雷达站',
    value: 'radarStation',
    LibID: 10,
    Code: 13800,
  },
  {
    label: '指挥车',
    value: 'commandVehicle',
    LibID: 10,
    Code: 5400,
  },
  {
    label: '指挥所',
    value: 'commandPost',
    LibID: 10,
    Code: 2804,
  },
  {
    label: '超短波天线',
    value: 'ultraShortWaveAntenna',
    LibID: 64,
    Code: 308,
  },
  {
    label: '微波天线',
    value: 'antenna',
    LibID: 64,
    Code: 298,
  },
  {
    label: '短波天线',
    value: 'shortWaveAntenna',
    LibID: 64,
    Code: 307,
  },
  {
    label: '机场',
    value: 'airport',
    LibID: 11,
    Code: 1001,
  },
  {
    label: '地标',
    value: 'landmark',
    LibID: 11,
    Code: 1002,
  },
  {
    label: '未知固定点(圆图标)',
    value: 'unknownFixedPoint',
    LibID: 11,
    Code: 1000,
  },
  {
    label: '静目标',
    value: 'quietTarget',
    LibID: 11,
    Code: 1000,
  },
  {
    label: '动目标',
    value: 'movingTarget',
    LibID: 64,
    Code: 7901,
  },
]

//
const ColorConverter = {
  // RGB 转十六进制
  rgbToHex(r, g, b) {
    if (typeof r === 'object') ({ r, g, b } = r)
    const toHex = (num) =>
      Math.max(0, Math.min(255, Math.round(num)))
        .toString(16)
        .padStart(2, '0')
    return `#${toHex(r)}${toHex(g)}${toHex(b)}`
  },

  // RGBA 转十六进制 (带透明度)
  rgbaToHex(r, g, b, a) {
    if (typeof r === 'object') ({ r, g, b, a } = r)
    const rgbHex = this.rgbToHex(r, g, b)
    const alphaHex = Math.round(Math.max(0, Math.min(1, a)) * 255)
      .toString(16)
      .padStart(2, '0')
    return `#${alphaHex}${rgbHex.substring(1)}`
  },

  // 十六进制转 RGB
  hexToRgb(hex, geshi) {
    const rgba = this.hexToRgba(hex)
    if (geshi == '默认') {
      return {
        r: rgba.r,
        g: rgba.g,
        b: rgba.b,
      }
    } else {
      return {
        color: {
          red: rgba.r,
          green: rgba.g,
          blue: rgba.b,
        },
      }
    }
  },

  // 十六进制转 RGBA
  hexToRgba(hex) {
    hex = hex.replace('#', '')
    let r, g, b, a

    if (hex.length === 8) {
      a = parseInt(hex.substring(0, 2), 16) / 255
      r = parseInt(hex.substring(2, 4), 16)
      g = parseInt(hex.substring(4, 6), 16)
      b = parseInt(hex.substring(6, 8), 16)
    } else if (hex.length === 6) {
      a = 1
      r = parseInt(hex.substring(0, 2), 16)
      g = parseInt(hex.substring(2, 4), 16)
      b = parseInt(hex.substring(4, 6), 16)
    } else if (hex.length === 4) {
      a = parseInt(hex[0] + hex[0], 16) / 255
      r = parseInt(hex[1] + hex[1], 16)
      g = parseInt(hex[2] + hex[2], 16)
      b = parseInt(hex[3] + hex[3], 16)
    } else if (hex.length === 3) {
      a = 1
      r = parseInt(hex[0] + hex[0], 16)
      g = parseInt(hex[1] + hex[1], 16)
      b = parseInt(hex[2] + hex[2], 16)
    } else {
      return null
    }

    return { r, g, b, a }
  },
}

// Color结构体
export const ColorStyle = (Colordata, num = 0) => {
  //   默认值RGB=[255,255,255,255]（白色，不透明）
  //   默认值RGB=[255,0,0,0]（黑色，不透明）
  if (num == 0) {
    // debugger
    // 兼容两种输入格式：扁平结构和嵌套color结构
    const colorData = Colordata?.color || Colordata

    if (iscolor(colorData) == 'hex') {
      let { r, g, b, a } = ColorConverter.hexToRgba(colorData)
      return {
        A: a * 255,
        R: r,
        G: g,
        B: b,
      }
    } else {
      return {
        A: colorData?.alpha || 255,
        R: colorData?.red || 0,
        G: colorData?.green || 0,
        B: colorData?.blue || 0,
      }
    }
  } else {
    if (typeof Colordata === 'string') {
      if (iscolor(Colordata) == 'rgb') {
        const match = Colordata.match(/^rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/)
        if (match) {
          return {
            A: 255,
            R: Number(match[1]),
            G: Number(match[2]),
            B: Number(match[3]),
          }
        }
      } else if (iscolor(Colordata) == 'rgba') {
        const match = Colordata.match(
          /^rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*([\d.]+)\s*\)$/,
        )
        if (match) {
          return {
            A: Math.round(Number(match[4]) * 255),
            R: Number(match[1]),
            G: Number(match[2]),
            B: Number(match[3]),
          }
        }
      } else {
        return ColorConverter.hexToRgb(Colordata)
      }
    }
    // 默认返回黑色不透明
    return {
      A: 255,
      R: 0,
      G: 0,
      B: 0,
    }
  }
}

// Line结构体
export const LineStyle = (LineStyledata) => {
  let showcolor = ColorStyle(ColorConverter.hexToRgb(LineStyledata.color, 'line'))
  return {
    ColorData: `rgba(${showcolor.R},${showcolor.G},${showcolor.B},${showcolor.A})`,
    LineStyle: 0,
    LineWidth: LineStyledata?.width,
    LineColor: showcolor,
  }
}

//  Font结构体
export const FontStyle = (FontStyledata, str) => {
  if (str == '字') {
    return {
      ForeColordata: FontStyledata.fillColor,
      BackColordata: FontStyledata.backgroundColor,
      FontName: '',
      FontSize: FontStyledata.scale,
      IsBold: '0',
      ForeColor: ColorStyle(FontStyledata.fillColor || FontStyledata),
      BackColor: FontStyledata.showBackground
        ? ColorStyle(FontStyledata.backgroundColor)
        : { A: 0, R: 0, G: 0, B: 0 },
    }
  } else {
    return {
      FontName: '',
      FontSize: 12,
      IsBold: 0, //0：不加粗；1：加粗；默认值=0
      ForeColor: ColorStyle(FontStyledata),
      BackColor: ColorStyle(FontStyledata),
    }
  }
}

// JIcon结构体
export const JIcon = (JIcondata, LibID = '静目标', str = '编辑', Lei) => {
  let colorarr = null
  if (str != '编辑') {
    colorarr = `rgba(${ColorStyle(ColorConverter.hexToRgb(JIcondata.color, 'line')).R},${ColorStyle(ColorConverter.hexToRgb(JIcondata.color, 'line')).G},${ColorStyle(ColorConverter.hexToRgb(JIcondata.color, 'line')).B},${ColorStyle(ColorConverter.hexToRgb(JIcondata.color, 'line')).A})`
  } else {
    if (iscolor(JIcondata.color) == 'no') {
      let col = ColorStyle(ColorConverter.hexToRgb(JIcondata.color, 'line'))
      colorarr = `rgba(${col.R},${col.G},${col.B},${col.A})`
    } else {
      colorarr = JIcondata.color
    }
  }
  return {
    ColorData: colorarr,
    IconColor: ColorStyle(JIcondata),
    IconSize: JIcondata?.pixelSize || 10,
    LibID: getArmyMarkValue(LibID).LibID,
    Code: getArmyMarkValue(LibID).Code,
    jbtype: LibID,
    Leixing: Lei,
  }
}

// Point3D结构体
export const Point3D = (Point3Ddata) => {
  // toFixed(6)
  return {
    Lon: Number(Point3Ddata[0]),
    Lat: Number(Point3Ddata[1]),
    Alt: Point3Ddata[2],
  }
}

// Point2D结构体
export const Point2D = (Point2Ddata) => {
  return {
    Lon: Point2Ddata[0],
    Lat: Point2Ddata[1],
  }
}

// Area结构体
export const Area = (Areadata) => {
  let { r, g, b, a } = ColorConverter.hexToRgba(Areadata.color)
  return {
    ColorData: `rgba(${r},${g},${b},${Areadata.colorAlpha})`,
    lineColorData: Areadata.outlineColor,
    LineStyle: Areadata.outline == true ? '0' : '1',
    LineWidth: Areadata?.outlineWidth,
    LineColor: ColorStyle(Areadata.outlineColor),
    FillColor: {
      A: Areadata.colorAlpha * 255,
      R: r,
      G: g,
      B: b,
    },
  }
}

//

export const iscolor = (color) => {
  const rgbRegex = /^rgb\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*\)$/
  const rgbaRegex = /^rgba\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*,\s*[\d.]+\s*\)$/
  const hexRegex = /^#([0-9A-Fa-f]{3}){1,2}$|^#([0-9A-Fa-f]{4}){1,2}$/

  if (rgbRegex.test(color)) {
    return 'rgb'
  } else if (rgbaRegex.test(color)) {
    return 'rgba'
  } else if (hexRegex.test(color)) {
    return 'hex'
  }
  return 'no'
}

// 此函数用于从 rgba 字符串中提取透明度值
export const extractAlphaFromRgba = (rgbaStr) => {
  const match = rgbaStr.match(/^rgba\(\d+,\s*\d+,\s*\d+,\s*(\d+(?:\.\d+)?)\)$/)
  if (match) {
    return Number(parseFloat(match[1]))
  }
  return null
}

// 示例调用
// const alphaValue = extractAlphaFromRgba('rgba(1,1,1,1)');
// console.log('提取的透明度值:', alphaValue);
